const Joi = require('@hapi/joi');
const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
module.exports = [
  {
    path: '/{date}/{filename}',
    method: 'GET',
    handler: (request, h) => {
      return h.file(path.join(request.params.date,request.params.filename));
    },
    options: {
      auth: false,
      files: {
        relativeTo: './upload'
      }
    }
  },
  {
    path: '/image',
    method: 'POST',
    handler: async (request, h) => {
      const originName = request.payload['file'].hapi.filename
      const saveName = crypto.randomBytes(Math.ceil(24 / 2)).toString('hex').slice(0, 24) + path.extname(originName);
      const savePath = './upload/' + require('../../utils/date.js').datestr()
      await fs.promises.mkdir(savePath, { recursive: true })
      const writable = fs.createWriteStream(path.join(savePath,saveName));
      request.payload['file'].pipe(writable)
      return h.response({
        filename: originName,
        filepath: savePath,
        filesize: '',
        fileext: '',
        uploader_id: '',
        is_cover: false,
        water: false,
        url: request.url.origin + '/file/' + path.join(savePath,saveName).substr(7),
        hash: '',
        module: ''
      });
    },
    options: {
      auth: false,
      payload: {
        allow: 'multipart/form-data',
        output: 'stream',
        parse: true,
        multipart: true,
        uploads: './upload',
        maxBytes: 1048576 * 5,
        timeout: 10000
      },
      tags: ['api', 'Attachment/Image'],
      description: '单张图片上传',
      notes: '单张图片上传',
      // validate: {
        // query: Joi.object({
        //   page: Joi.number().integer().positive().min(1).default(1).description('分页页码'),
        //   sort: Joi.string().default('id').description('排序字段'),
        //   descending: Joi.boolean().default('false').description('是否desc'),
        //   page_size: Joi.number().integer().min(-1).default(20).description('分页容量'),
        //   trashed: Joi.boolean().default('false').description('是否显示已删除内容'),
        // }).label('SearchCondition')
      // },
      response: {
        schema: Joi.object()
      }
    }
  }
]